package com.zoe.onelink.actuate.check;

import com.zoe.onelink.plugin.check.AbstractEnvironmentChecker;
import com.zoe.onelink.plugin.check.model.PropertyCheckResult;
import com.zoe.onelink.util.StrUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.jdbc.metadata.DataSourcePoolMetadata;
import org.springframework.boot.jdbc.metadata.DataSourcePoolMetadataProvider;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-09-21
 */
@RequiredArgsConstructor
public class DatasourceEnvironmentChecker extends AbstractEnvironmentChecker {

    @Override
    public List<PropertyCheckResult<?>> doCheck() {
        List<DataSourcePoolMetadataProvider> dataSourcePoolMetadataProviders = this.getBeanList(DataSourcePoolMetadataProvider.class);
        DataSource dataSource = this.getBean(DataSource.class);
        List<PropertyCheckResult<?>> propertyCheckResults = new ArrayList<>();
        for (DataSourcePoolMetadataProvider dataSourcePoolMetadataProvider : dataSourcePoolMetadataProviders) {
            DataSourcePoolMetadata dataSourcePoolMetadata = dataSourcePoolMetadataProvider.getDataSourcePoolMetadata(dataSource);
            if (dataSourcePoolMetadata == null) {
                continue;
            }
            Integer maxActive = dataSourcePoolMetadata.getMax();
            if (maxActive != null && maxActive < 50) {
                String msg = StrUtil.format("数据库连接池最大连接数配置小于50,可能存在连接数不足问题");
                PropertyCheckResult<Integer> checkResult = new PropertyCheckResult<Integer>()
                        .setPropKey("数据库最大连接数")
                        .setPropValue(maxActive)
                        .setLevel(PropertyCheckResult.Level.DANGER)
                        .setMessage(msg);
                propertyCheckResults.add(checkResult);
            }
        }
        return propertyCheckResults;
    }

}
